<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Models\Device;
use App\Models\ProjectUser;
use App\Models\ProjectPlan;
use Hash;
use Log;
//20210519
class SmokeController extends Controller
{
    public function adddevice(Request $request){
        $info = $request->all();
        $device = Db::table('xfy_device')->where(['cid'=>$info['cid']])->first();
        if($device){
            $res['status'] = 0;
            $res['msg'] = '该设备已添加过！';
            return json_encode($res);
        }
        // $str = '869512030307544'; //霍尼
        // $str1 = '02_NB_8653520362445710'; //川大
        // print_r(strlen($str).':'.strlen($str1));die;
        $info['cid'] = strlen($info['cid'])==22?substr($info['cid'],6,15):$info['cid'];
        $type = strlen($info['cid'])==22?2:1;
        $add_res = $this->deviceAdd($info['cid'],$type);
        if(isset($add_res['error_code'])){ //添加失败
            $res['status'] = 0;
            $res['msg'] = $add_res['error_desc'];
        }else{
            $arr = explode(",", $info['picker']);
            $info['province'] = $arr[0];
            $info['city'] = $arr[1];
            $info['area'] = $arr[2];
            unset($info['picker']);
            unset($info['_url']);
            $info['created_at'] = date("Y-m-d H:i:s");
            $info['updated_at'] = date("Y-m-d H:i:s");
            $info['avatar'] = trim($info['avatar'],'"');
            $info['gatewayId'] = $add_res['deviceId'];
            $id = Db::table('xfy_device')->insertGetId($info);
            $res['status'] = 1;
            $res['msg'] = '添加成功';
        }
        return json_encode($res);
    }
    //添加设备
    //imei 长度15为霍尼，22为川大
    public function deviceAdd($imei,$device_type){// GDHS90BWNB
        if (!Cache::has('authtoken')) { //鉴权
            $this->authentication();
        }
        if($device_type==1){ //霍尼
            $dtype = 'GDHS90BWNB';
            $manu = 'Hisense';
            $devicetype = 'Smoke';
        }elseif ($device_type==2) { //川大
            $dtype = 'NB20';
            $manu = 'Cdsoft';
            $devicetype = 'Smoke';
        }
        // $dtype = $device_type==2?'NB20':'GDHS90BWNB';
        // $manu = $device_type==2?'Cdsoft':'Hisense';
        $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
        $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        $data = '{"verifyCode":"'.$imei.'","nodeId":"'.$imei.'","deviceInfo":{"manufacturerId":"'.$manu.'","manufacturerName":"'.$manu.'","deviceType":"'.$devicetype.'","model":"'.$dtype.'","protocolType":"CoAP"}}';
        $a = $this->postSsl($url,$data,$header);
        $res = json_decode($a['return'],1);
        return $res;
    }

    public function Smokedevice(Request $request){
        $info = $request->all();
        $device = Device::where(['xfy_device.deviceId'=>$info['deviceId']])
                ->join('xfy_project','xfy_project.projectId','=','xfy_device.projectId')
                ->select('xfy_device.*','xfy_project.projectname')
                ->first()->toArray();
        if(isset($device['planeJPG'])){
            $plane = ProjectPlan::where(['id'=>$device['planeJPG']])->first()->toArray();
            $device['image'] = $plane['image'];
        }
        // $body['resultCode'] = 0;
        // $body['resultBody']['resultMsg'] = '暂无数据';
        // if($device){
        //     $body['resultBody']['url'] = 'https://open.ys7.com/v3/openlive/F46330057_1_2.m3u8?expire=1620816672&id=312300630613438464&t=670011545f193e1310b1e19080e0ae8b802892fa4ea5d8886682aaef70684984&ev=100';//临时直播地址
            $body['resultBody']['device'] = $device;
            $body['resultCode'] = 1;
        // }
        return json_encode($body);
    }

    //设置回调地址
    public function SetCallback(){
        if (!Cache::has('authtoken')) { //鉴权
            $this->authentication();
        }
        //设置回调
        $url = 'https://device.api.ct10649.com:8743/iocm/app/sub/v1.2.0/subscriptions';
        $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        // $data = '{"notifyType":"deviceAdded","callbackUrl":"http://xbxfy.benpuji.com/api/deviceAdd","channel":"HTTP"}';
        $data = '{"notifyType":"deviceInfoChanged","callbackUrl":"http://yun.xmcitypower.com/api/deviceInfo","channel":"HTTP"}';
        // $data = '{"notifyType":"deviceDataChanged","callbackUrl":"http://yun.xmcitypower.com/api/deviceData","channel":"HTTP"}';
        $a = $this->postSsl($url,$data,$header);
        print_r($a);die;
    }

    //鉴权
    public function authentication(){
        $data = 'appId=86y97uYn78Try5i1zFdTLiErnX4a&secret=aayy3kB2YJGh1FCpeyxGsyC_uCAa';
        $url = 'https://device.api.ct10649.com:8743/iocm/app/sec/v1.1.0/login';
        $header = ["Content-Type" => "application/x-www-form-urlencoded;"];//貌似不需要,默认就是
        $a = $this->postSsl($url,$data,$header);
        if($a['status']==1){
            $return = json_decode($a['return'],1);
            Cache::add('authtoken', $return['accessToken'], 3000);
        }
    }


    function postSsl($url, $data, $header) {
        // if (is_array($data)) {
        //     $data = http_build_query($data);
        // }
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(__FILE__))).'/server.crt'); //证书
        curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(__FILE__))).'/server.key'); //证书
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        $ret = ['status' => 1];
        if ($error = curl_errno($curl)) {
            $ret['status'] = 0;
            $ret['return'] = $error;
        } else {
            $ret['return'] = $res;
        }
        curl_close($curl); // 关闭CURL会话
        return $ret; // 返回数据
    }
}